"use client";
/**
 * @license 敏捷之道软件
 * 商业用途必须获得书面授权
 * 侵权举报: ideaswork@qq.com
 * 法律依据:《计算机软件保护条例》第二十四条
 */
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardTitle } from "@/components/ui/card"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { ChevronDownIcon, SettingsIcon } from "lucide-react"
import Link from "next/link"
import { Map, ListTodo, TrendingUpIcon, CheckSquare, Users, BarChart2 , Briefcase,Gauge, FileIcon, FileBox } from "lucide-react"
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Skeleton } from "@/components/ui/skeleton";
import { Product } from "@/types/Model";

interface MenuItem {
  href: string;
  title: string;
  content: string;
  icon: React.ElementType;
  color: string;
  roles: string[];
}


export default function Workspace() {
  const [products, setProducts] = React.useState([]);
  const router = useRouter();
  const [currentProduct, setCurrentProduct] = useState<Product>();
  const [userRole, setUserRole] = useState<string>('');
  const [menuItems, setMenuItems] = useState<MenuItem[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchUserData = async () => {
    try {
      const response = await fetch('/api/auth/me');
      if (!response.ok) throw new Error('Failed to fetch user data');
      return await response.json();
    } catch (error) {
      console.error('Failed to fetch user data', error);
      router.push('/login');
      return null;
    }
  };

  const fetchProductData = async () => {
    try {
      const response = await fetch('/api/product');
      if (!response.ok) throw new Error('Failed to fetch products');
      return await response.json();
    } catch (error) {
      console.error('Failed to fetch products', error);
      return [];
    }
  };

  useEffect(() => {
    const initializeData = async () => {
      const [productsData, userData] = await Promise.all([
        fetchProductData(),
        fetchUserData()
      ]);

      if (!userData) return;

      setProducts(productsData);
      setUserRole(userData.role);
      
      if (productsData.length > 0) {
        const storedProduct = localStorage.getItem('currentProduct');
        const selectedProduct = storedProduct ? JSON.parse(storedProduct) : productsData[0];
        setCurrentProduct(selectedProduct);
        if (!storedProduct) {
          localStorage.setItem('currentProduct', JSON.stringify(selectedProduct));
        }
      }

      const filteredItems = getMenuItems(userData.role);
      setMenuItems(filteredItems);
      setLoading(false);
    };

    initializeData();
  }, [router]);

  const handleProductChange = (product: any) => {
    setCurrentProduct(product);
    localStorage.setItem('currentProduct', JSON.stringify(product));
  }

  const handleManageProducts = () => {
    router.push('/product');
  }

  const getMenuItems = (role: string) => {
    const allMenuItems = [
      // { 
      //   href: "/product", 
      //   title: "产品管理", 
      //   content: "管理和配置产品",
      //   icon: Briefcase,
      //   color: "text-teal-500",
      //   roles: ['Scrum Master']
      // },
      {
        href: "/notion",
        title: "文档管理",
        content: "项目管理相关文档",
        icon: FileBox,
        color: "text-orange-500",
        roles: ['Product Owner', 'Scrum Master']
      },
      {
        href: "/userstory",
        title: "用户故事",
        content: "管理用户故事地图",
        icon: Map,
        color: "text-blue-500",
        roles: ['Product Owner', 'Scrum Master']
      },
      {
        href: "/backlog",
        title: "产品待办",
        content: "查看和管理产品待办",
        icon: ListTodo,
        color: "text-green-500",
        roles: ['Product Owner', 'Scrum Master']
      },
      { 
        href: "/sprint", 
        title: "Sprint 冲刺", 
        content: "创建和管理冲刺",
        icon: TrendingUpIcon,
        color: "text-yellow-500",
        roles: ['Scrum Master']
      },
      { 
        href: "/task", 
        title: "任务", 
        content: "分配和跟踪任务",
        icon: CheckSquare,
        color: "text-purple-500",
        roles: ['Team Member', 'Scrum Master', 'Product Owner']
      },

      { 
        href: "/team", 
        title: "团队管理", 
        content: "管理用户和权限",
        icon: Users,
        color: "text-red-500",
        roles: ['Scrum Master']
      },
      {
        href: "/dashboard",
        title: "产品报表",
        content: "查看冲刺和产品燃尽图",
        icon: Gauge,
        color: "text-indigo-500",
        roles: ['Team Member', 'Scrum Master', 'Product Owner']
      },
      {
        href: "/worklog/user",
        title: "工作统计",
        content: "查看工作统计",
        icon: BarChart2,
        color: "text-orange-500",
        roles: ['Team Member', 'Scrum Master', 'Product Owner']
      },
      {
        href: "/system",
        title: "系统设置",
        content: "系统设置",
        icon: SettingsIcon,
        color: "text-blue-500",
        roles: ['Scrum Master']
      },
      // {
      //   href: "/worklog/scrum-master",
      //   title: "工作统计",
      //   content: "查看工作统计",
      //   icon: BarChart2,
      //   color: "text-orange-500",
      //   roles: [ 'Scrum Master',]
      // },
 
    ];

    const filteredItems = allMenuItems.filter(item => {
      return item.roles.includes(role);
    });

    return filteredItems;
  }

  return (
    <div className="flex flex-col min-h-screen bg-gradient-to-b from-white to-gray-50 dark:from-gray-950 dark:to-gray-900">
  <div className="container mx-auto px-4 md:px-6 py-12 md:py-16">
    {/* Header Section with Larger Typography */}
    <div className="mb-12 md:mb-16 text-center">
      <h1 className="text-4xl md:text-5xl font-bold text-gray-900 dark:text-white mb-4 tracking-tight">
        敏捷之道 <span className="text-blue-600 dark:text-blue-400">Agiledao</span>
      </h1>
      <p className="text-gray-600 dark:text-gray-300 text-xl md:text-2xl">
        极简敏捷开发管理工具
      </p>
    </div>

    {/* Product Selection Card with Improved Text Clarity */}
    <div className="backdrop-blur-sm bg-white/90 dark:bg-gray-800/90 shadow-md rounded-2xl p-6 md:p-8 mb-12">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div className="space-y-2">
          <p className="text-base md:text-lg font-medium text-gray-500 dark:text-gray-400">当前产品</p>
          <h2 className="text-2xl md:text-3xl font-semibold text-gray-800 dark:text-gray-100">
            {currentProduct?.name ?? "未选择产品"}
          </h2>
        </div>
        
        <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-4 w-full sm:w-auto">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="outline"
                className="w-full sm:w-auto bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg font-medium text-base md:text-lg px-6 py-3"
              >
                <span>切换产品</span>
                <ChevronDownIcon className="h-5 w-5 ml-2 opacity-70" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-64 bg-white dark:bg-gray-800 shadow-lg rounded-lg border-0">
              {products.map((product: any) => (
                <DropdownMenuItem
                  key={product.id}
                  onClick={() => handleProductChange(product)}
                  className="cursor-pointer focus:bg-gray-100 dark:focus:bg-gray-700 text-base md:text-lg py-3"
                >
                  {product.name}
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          
          {userRole === 'Scrum Master' && (
            <Button
              variant="outline"
              onClick={handleManageProducts}
              className="w-full sm:w-auto text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 text-base md:text-lg px-6 py-3"
            >
              管理产品
            </Button>
          )}
        </div>
      </div>
    </div>

    {/* Menu Grid with Larger Text Cards */}
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8">
      {loading ? (
        Array.from({ length: 9 }).map((_, index) => (
          <Card key={index} className="rounded-xl border-0 shadow-md overflow-hidden ">
            <CardContent className="p-8  r">
              <div className="flex items-center mb-6">
                <Skeleton className="w-10 h-10 rounded-full" />
                <div className="ml-4 flex-1">
                  <Skeleton className="h-8 w-32" />
                </div>
              </div>
              <Skeleton className="h-6 w-full mt-3" />
              <Skeleton className="h-6 w-3/4 mt-3" />
            </CardContent>
          </Card>
        ))
      ) : (
        menuItems?.map((item) => (
          <Link href={item.href} key={item.href} className="block group">
            <Card className="rounded-xl border-0 shadow-md dark:bg-gray-800 h-full hover:shadow-lg transition-all duration-200 overflow-hidden ">
              <CardContent className="p-8 ">
                <div className="flex items-center mb-4">
                  <div className={`p-3 rounded-lg bg-opacity-15 ${getIconBackgroundColor(item.color)}`}>
                    {item.icon && <item.icon className={`w-8 h-8 ${item.color}`} />}
                  </div>
                  <CardTitle className="text-xl md:text-2xl font-semibold text-gray-800 dark:text-gray-200 ml-4">
                    {item.title}
                  </CardTitle>
                </div>
                <p className="text-gray-600 dark:text-gray-400 text-base md:text-lg leading-relaxed mt-2">
                  {item.content}
                </p>
              </CardContent>
            </Card>
          </Link>
        ))
      )}
    </div>
  </div>
</div>
  )
}


{/* Helper function to get appropriate background color */}
function getIconBackgroundColor(color: string) {
  if (color.includes('blue')) return 'bg-blue-100 dark:bg-blue-900/30';
  if (color.includes('green')) return 'bg-green-100 dark:bg-green-900/30';
  if (color.includes('red')) return 'bg-red-100 dark:bg-red-900/30';
  if (color.includes('yellow')) return 'bg-yellow-100 dark:bg-yellow-900/30';
  if (color.includes('purple')) return 'bg-purple-100 dark:bg-purple-900/30';
  if (color.includes('pink')) return 'bg-pink-100 dark:bg-pink-900/30';
  if (color.includes('indigo')) return 'bg-indigo-100 dark:bg-indigo-900/30';
  return 'bg-gray-100 dark:bg-gray-800';
} 